﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace Magic.Web.Core.Handlers.Tcp
{
    public partial class TcpServicePlugin : PluginBase
    {
        private readonly ILogger<TcpServicePlugin> m_logger;

        public TcpServicePlugin(ILogger<TcpServicePlugin> logger)
        {
            this.m_logger = logger;
        }

        [GeneratorPlugin(nameof(ITcpConnectedPlugin.OnTcpConnected))]
        public async Task OnTcpConnected(ITcpClientBase client, ConnectedEventArgs e)
        {
            m_logger.LogInformation("Tcp客户端已连接。信息：{0}", client.GetIPPort());
            await e.InvokeNext();
        }

        [GeneratorPlugin(nameof(ITcpDisconnectedPlugin.OnTcpDisconnected))]
        public async Task OnTcpDisconnected(ITcpClientBase client, DisconnectEventArgs e)
        {
            m_logger.LogInformation("Tcp客户端已断开。信息：{0}，断开信息：{1}", client.GetIPPort(),e.Message);
            await e.InvokeNext();
        }

        [GeneratorPlugin(nameof(ITcpReceivedPlugin.OnTcpReceived))]
        public async Task OnTcpReceived(ITcpClientBase client, ReceivedDataEventArgs e)
        {
            m_logger.LogInformation("Tcp收到信息：{0}", Encoding.UTF8.GetString(e.ByteBlock.ToArray()));
            await e.InvokeNext();
        }
    }
}
